package com.weds.data_sync.advice;

import com.weds.data_sync.advice.exception.BizCodeException;
import com.weds.data_sync.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 全局异常处理
 * @Author lihw
 * @Date 2024/1/4 9:47
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public JsonData handler(Exception e) {
        e.printStackTrace();
        return JsonData.buildError(e.getMessage());
    }

    @ExceptionHandler(value = BizCodeException.class)
    public JsonData handlerBizCodeException(BizCodeException e) {
        log.info("错误信息: {}", e.getMessage());
        return JsonData.buildResult(e.getBizCodeEnum());
    }

    /**
     * 字段校验错误处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonData handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return JsonData.buildError(errorMessage);
    }
}
